﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Corsat.Library.DataManager;
using Corsat.Library.Logic;

namespace Corsat.Web._2013
{
    public partial class Exam : System.Web.UI.Page
    {
        public int AccountId
        {
            get
            {
                int id = 0;
                if (Session["accountId"] != null)
                {
                    int.TryParse(Session["accountId"].ToString(), out id);
                }
                return id;
            }
        }

        public int CourseId
        {
            get
            {
                if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "")
                {
                    return System.Convert.ToInt32(Request.QueryString["cid"].ToString());
                }
                return 0;
            }
        }

        public List<Question> ExamQuestions
        {
            get
            {
                string examQuestionsSessionId = "examQuestions_" + AccountId + "_" + CourseId + "_";
                if (Session[examQuestionsSessionId] != null)
                {
                    return (List<Question>)Session[examQuestionsSessionId];
                }
                return null;
            }
            set
            {
                string examQuestionsSessionId = "examQuestions_" + AccountId + "_" + CourseId + "_";
                Session[examQuestionsSessionId] = value;
            }
        }

        public bool EnableExam
        {
            get
            {
                bool value = false;
                if (WebConfigurationManager.AppSettings["enableOnlineExams"] != null)
                {
                    bool.TryParse(WebConfigurationManager.AppSettings["enableOnlineExams"], out value);
                }
                return value;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (AccountId > 0 && EnableExam)
            {
                int cid = -1;
                bool isExamAvailable = Main.CanAttendCourseId(AccountId, CourseId);
                if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "" && isExamAvailable)
                {
                    var courseData = Main.GetCourseById(CourseId);
                    course_lbl.Text = courseData.CourseName;
                    hdnAccountId.Value = AccountId.ToString();
                    hdnSelectedCourseId.Value = CourseId.ToString();
                    if (ExamQuestions == null || ExamQuestions.Count == 0)
                    {
                        ExamQuestions = Main.GetCourseRandomExam(CourseId);
                    }

                    hdnCount.Value = ExamQuestions.Count.ToString();
                    questionRepeater.DataSource = ExamQuestions;
                    questionRepeater.DataBind();
                }
                else
                {
                    //redirect to error
                    Response.Redirect("~/Profile.aspx");
                }
            }
            else
            {
                //redirect to error
                Response.Redirect("~/Profile.aspx");
            }
        }

        [WebMethod]
        public static string Save(List<AnswerModel> answers, int courseId, int accountId, int count)
        {
            //return Main.UpdateAccountData(account);
            int attendanceCount = 0;
            var rightAnswers = Main.GetQuestionRightAnswers(answers.Select(x => x.QuestionId).ToList(), out attendanceCount,accountId,courseId);
            int result = 0;
            var resultsText = "";
            if (rightAnswers != null)
            {
                foreach (AnswerModel answerModel in answers)
                {
                    if (rightAnswers.Any(ra=>ra.QuestionId ==answerModel.QuestionId && ra.AnswerId ==answerModel.AnswerId))
                    {
                        result++;
                    }
                }
            }
            result += (attendanceCount*5);

            // Get Questions Count
            var questionsCount = count;
            questionsCount += 35;


            resultsText = " لقد حصلت على " + " " + result.ToString() + " " + " من " + questionsCount;
            //results.Visible = true;
            //linkHome.Visible = true;

            float percentage = ((float)result / questionsCount);

            percentage = (float)Math.Round(percentage, 4);

            Main.UpdateAccountCourseGrade(accountId, courseId, (percentage * 100));
            return resultsText;
        }
    }

    public class AnswerModel
    {
        public int AnswerId { get; set; }
        public int QuestionId { get; set; }
    }
}